<?php

namespace App\Service;
use App\Service\CommService;
use App\Service\TaskService;
use Hyperf\DbConnection\Db;
use Hyperf\Cache\Annotation\Cacheable;
use Hyperf\Cache\Annotation\CachePut;
use App\Service\UserService;
use App\Service\PlayletService;
use App\Service\WxPayService;
use Hyperf\Utils\ApplicationContext;
use Hyperf\Database\Transaction\Transaction;



class RechargeService extends CommicService
{
    private UserService $userService;
    private PlayletService $playletService;
    private TaskService $taskService;
    private WxPayService $wxPayService;

    private DyService $dyService;
    private CommService $commService;

    public function __construct( DyService $dyService,UserService $userService,PlayletService $playletService,TaskService $taskService,CommService $commService,WxPayService $wxPayService)
    {
        $this->userService = $userService;
        $this->playletService = $playletService;
        $this->taskService = $taskService;
        $this->commService = $commService;
        $this->dyService = $dyService;
        $this->wxPayService = $wxPayService;
        $container = ApplicationContext::getContainer();
        $this->redis = $container->get(\Hyperf\Redis\Redis::class);
    }
    public function goods_list($applet_id,$spread_id=0,$ispay=0){

        $template_info = $this->get_template($spread_id,$ispay);
        $recd_data = Db::table('recharge_template_goods_rel as rec_rel')
            ->join('recharge_goods', function ($join)use ($template_info) {
                $join->on('rec_rel.recharge_goods_id', '=', 'recharge_goods.id')
                    ->where([
                        ["rec_rel.recharge_template_id","=",$template_info->id]
                    ]);
            })
            ->select(
                "rec_rel.recharge_goods_id",
                "rec_rel.is_highlight",
                "rec_rel.is_default",
                "recharge_goods.amount",
                "recharge_goods.name",
                "recharge_goods.ml_coin",
                "recharge_goods.give_coin",
                "recharge_goods.prompt2",
                "recharge_goods.type",
                "recharge_goods.day",
                "recharge_goods.bgtype",
                "recharge_goods.classtext",
                "recharge_goods.classbgc",
                "recharge_goods.classcolor",
                "recharge_goods.amountcolor",
                "recharge_goods.footicon",
                "recharge_goods.foottext",
                "recharge_goods.footcolor",
                "recharge_goods.giftcolor"
            )->orderBy("rec_rel.sort","desc")->get();

        $recd_data = $this->object_to_array($recd_data);
        if ($recd_data){
            $applet_info = $this->userService->get_user_applet_info($applet_id);
            foreach ($recd_data as $key =>$val){
                $recd_data[$key]["amount_name"] = number_format($val["amount"]/100,2);
                $recd_data[$key]["amount"] = $val["amount"]/100;
                if ($val["give_coin"]>0){
                    $recd_data[$key]["give_coin"] =$val["give_coin"];
                    $recd_data[$key]["coin_name"] = $applet_info["coin_name"];
                    $recd_data[$key]["ml_coin"] = (string)$val["ml_coin"];
                }else{
                    if ($val["type"] == 3){
                        $recd_data[$key]["ml_coin"] = $val["name"];
                        $recd_data[$key]["give_coin"] = 0;
                        $recd_data[$key]["coin_name"] = "全场剧集免费看";
                    }else{
                        $recd_data[$key]["ml_coin"] =$val["ml_coin"].$applet_info["coin_name"];
                        $recd_data[$key]["give_coin"] = $val["give_coin"];
                        $recd_data[$key]["coin_name"] = $applet_info["coin_name"];
                    }
                }
            }
        }
        return $recd_data;
    }
    public function get_applet_id($order_id)
    {
        $res = Db::table('data_payment')->select('applet_id')->where('order_id',$order_id)->first();
        return $res;
    }
    public function get_applet(string $applet_id)
    {
        # 获取小程序基本配置
        $redis_key = "applet:config";
        $applet_info = $this->redis->hGet($redis_key,$applet_id);
        $applet_info = json_decode($applet_info,true);
        if (empty($applet_info)){
            # 获取小程序基本信息
            $applet_info = Db::table("applet")->where([
                "id"=>$applet_id
            ])->first();
            $applet_info = $this->object_to_find_array($applet_info);
            $this->redis->hSet($redis_key,$applet_id,json_encode($applet_info));
        }
        return $applet_info;
    }
    public function get_user_goods_list($applet_id,$user_id){
        echo "applet_id".$applet_id.PHP_EOL;
        echo "user_id".$user_id.PHP_EOL;
        # 判断当前用户是否充值
        $user_info = $this->userService->user_info($applet_id,$user_id);
        $data_payment = Db::table('data_payment')->select('id')
            ->where('user_id',$user_id)
            ->where('status',2)
            ->where('applet_id',$applet_id)
            ->where('spread_id',$user_info->spread_id)
            ->first();
        if(!empty($data_payment)){
            $ispay = 1;
        }  else {
            $ispay = 0;
        }
        $list = $this->goods_list($applet_id,$user_info->spread_id,$ispay);
        //2024-03-29 新增用户
        $coupon_list = $this->coupon_list($applet_id,$user_info);
        $rec_data = [
            "user_info"=>[
                "ml_coin"=>$user_info->ml_coin,
                "give_coin"=>$user_info->give_coin,
            ],
            "goods_list"=>$list,
            "coupon_list" => $coupon_list
        ];
        return $rec_data;
    }
    /**
     * 获取用户未使用，未过期的券
     * author bobo
     * date 2024-03-29
     */
    public function coupon_list($applet_id,$user_info){

        $returnData = array();
        $nowTime = date('Y-m-d H:i:s',time());


        $returnData = Db::table('data_user_coupon')
            ->select(['applet_coupon.name','data_user_coupon.coupon_id','data_user_coupon.valid_end_time'])
            ->where(['data_user_coupon.applet_id' => $applet_id,'data_user_coupon.user_id' => $user_info->id,'data_user_coupon.is_use' => 'N'])
            ->where('data_user_coupon.valid_begin_time','<=',$nowTime)
            ->where('data_user_coupon.valid_end_time','>=',$nowTime)
            ->leftJoin('applet_coupon','applet_coupon.id','=','data_user_coupon.applet_coupon_id')
            ->get();


        return $returnData;
    }
    public function goods_info($goods_id){
        $goods_info = Db::table("recharge_goods")->where(["id"=>$goods_id])->select("name","amount","ml_coin","give_coin","day","type")->first();
        return $goods_info;
    }

    public function get_order_id($applet_id,$user_id,$goods_id){
        $order_id = time().mt_rand(10000,99999).$applet_id.$user_id.$goods_id;
        return $order_id;
    }
    #查询微信余额
    public function check_balance($applet_id,$xc_open_id) {
        $user_info = $this->userService->get_xc_open_id_info($applet_id,$xc_open_id);
        $balance = $this->commService->query_user_balance($applet_id,$user_info);
        var_dump($balance);
        if($balance == false) {

            return 0;
        } else {
            return $balance['balance'];
        }
    }
    public function currency_pay($applet_id,$user_info,$amount,$order_id){
        $res = $this->commService->currency_pay($applet_id,$user_info,$amount,$order_id);
        var_dump('支付');
//        var_dump($res);
        if($res == false) {
            return 0;
        } else {
            return 1;
        }
    }
    public function buy_playlet($applet_id,$user_id,$playlet_id,$playlet_number){
        # 购买短剧
        $rec_data["code"]=10000;
        $user_info = $this->userService->user_info($applet_id,$user_id);
        var_dump('购买短剧');
        $playlet_number_info = $this->playletService->episodes_info($playlet_id,$playlet_number);
        if ($user_info->vip_effective_time > 0){
            $vip_effective_time = strtotime($user_info->vip_effective_time);
        }else{
            $vip_effective_time = 0 ;
        }
        if ($user_info->is_vip and $vip_effective_time>time()){
            return $rec_data;
        }else{
            $table_name = "data_user_".$applet_id;
            # 是否购买本级数
            $my_playlet_episodes = $this->playletService->get_my_playlet_episodes($applet_id,$user_id,$playlet_id);
            if (!in_array($playlet_number,$my_playlet_episodes)){
                $user_m_coin = $user_info->ml_coin + $user_info->give_coin;
                $amount = $playlet_number_info["amount"];
                if($user_info->spread_id) {
                    $data_spread = DB::table('data_spread')->where('id',$user_info->spread_id)->first();
                    if($data_spread->playlet_id == $playlet_id) {
                        $amount = $data_spread->playlet_number_num_pay>0?$data_spread->playlet_number_num_pay:$amount;
                    }
                }
                if ($user_m_coin >= $amount){
                            // 在事务中执行相关的数据库操作
                            #调用扣币接口
                            #微信扣
                            $order_id = $applet_id.$playlet_id.$playlet_number.$user_id;
                            var_dump('扣除-----');
                            #内部扣
                            if ($user_info->give_coin>$amount){
                                $user_update["give_coin"] = $user_info->give_coin-$amount;
                            }else{
                                $user_update["give_coin"] = 0;
                                $y_coin = $amount - $user_info->give_coin;
                                $user_update["ml_coin"] = $user_info->ml_coin-$y_coin;
                            }
                            $add_data = [
                                "user_id"=>$user_id,
                                "applet_id"=>$applet_id,
                                "playlet_id"=>$playlet_id,
                                "playlet_number"=>$playlet_number,
                                "amount"=>$playlet_number_info["amount"],
                                "order_id"=>$order_id,
                            ];
                            Db::table("data_user_pay_playlet_log")->insertGetId($add_data);
                            Db::table($table_name)->where(["id"=>$user_id])->update($user_update);
                            $this->userService->update_user_info($applet_id,$user_id);
                            $this->playletService->up_my_playlet_episodes($applet_id,$user_id,$playlet_id);
                            $this->taskService->do_task($applet_id,$user_id,3);
                            #2024-02-23 合并剧集
                            $this->playletService->set_merge_playlet_id($playlet_id,$user_id);
                }else{

                    $rec_data["code"] = 20061;
                }
            }
        }
        return  $rec_data;

    }
    public function get_sign($applet_id,$xc_open_id,$signDate) {
        $redis_key = 'login_info:'.$applet_id;
        $login_info = $this->redis->hGet($redis_key,$xc_open_id);
        $login_info = json_decode($login_info,true);
        $session_key = $login_info['session_key'];
        $url = "requestVirtualPayment";
        $res_data['signature'] = $this->commService->get_signature($signDate,$session_key);
        $res_data['paySig'] = $this->commService->get_paySig($applet_id,$url,$signDate);
        return $res_data;
    }
    public function buy_ios($applet_id,$user_id,$goods_id){
        $buy_info = $this->buy($applet_id,$user_id,$goods_id);

        $res = $this->wxPayService->unifyPay($buy_info);
        return $res;
        #小程序信息

        #
    }
//    public function buy($applet_id,$user_id,$goods_id){
    public function buy($applet_id,$user_id,$goods_id,$playlet_id,$pay_type=1,$user_platform=1){
        # 商品信息
        $goods_info = $this->goods_info($goods_id);
        $user_info = $this->userService->user_info($applet_id,$user_id);
        #注意vip和普通不一样.vip需要支付完成后扣除所有币
        $is_vip = 0;
        if ($goods_info->type == 3){
            $is_vip = 1;
        }
        # 去第三方支付
        $add_data = [
            "user_id"=>$user_id,
            "ad_id"=>$user_info->ad_id,
            "applet_id"=>$applet_id,
            "order_id"=>$this->get_order_id($applet_id,$user_id,$goods_id),
            "merchant_id"=>$user_info->merchant_id,
            "spread_id"=>$user_info->spread_id,
            "is_vip"=>$is_vip,
            "type"=>2,
            "pay_type"=>3,
            "ml_coin"=>$goods_info->ml_coin,
            "give_coin"=>$goods_info->give_coin,
            "amount"=>$goods_info->amount,
//            "pay_type"=>$pay_type,
            "playlet_id"=>$playlet_id,
            "goods_id"=>$goods_id,
            "order_time"=>date("Y-m-d H:i:s"),
            "user_platform"=>$user_platform,
        ];
        Db::table("data_payment")->insertGetId($add_data);
        $res_data["xc_open_id"] = $user_info->xc_open_id;
        $res_data["amount"] = $add_data["amount"];
        # 支付回掉
        $res_data['order_id'] = $add_data["order_id"];

//        $this->buyback($recdata);
        return $res_data;
    }

    public function  buyback($recdata,$type=1){
        co(function () use ($recdata,$type) {
            $order_id = $recdata["out_order_no"];
            $pay_time = $recdata['event_time'];
            $way = $recdata['pay_channel'];
            if($way == 1) {
                $way = 3;
            }elseif ($way == 2) {
                $way = 4;
            }elseif ($way == 10) {
                $way = 5;
            }
            $transaction_id = $recdata['channel_pay_id'];
            $order_info  = Db::table("data_payment")->where(["order_id"=>$order_id])->first();
            if(empty($order_info)) {
                var_dump('没有订单');
                return false;
            }
            var_dump('支付回调');
            if($order_info->status == 2) {
                var_dump('已支付');
                return false;
            }
            #ok 那就调用增加币和赠送币
            # 支付一步回掉
            $goods_info = $this->goods_info($order_info->goods_id);
            $applet_id = $order_info->applet_id;

            $user_id = $order_info->user_id;


            $user_info = $this->userService->user_info($applet_id,$user_id);

            $recharge_type = 1;
            $log_name = "充值成功";
            if ($goods_info->type == 3){
                $recharge_type  = 2;
                $log_name = "购买VIP".$goods_info->name;
                $day = $goods_info->day;
                if ($user_info->vip_effective_time > 0 && strtotime($user_info->vip_effective_time) >time()){
                    $vip_effective_time = date("Y-m-d H:i:s",strtotime($user_info->vip_effective_time.'+'.$day.'days'));
                    echo "lai".PHP_EOL;
                }else{
                    $vip_effective_time = date("Y-m-d H:i:s",strtotime('+'.$day.'day'));
                }
                echo "过期时间".$vip_effective_time.PHP_EOL;
                $user_update["is_vip"] = 1;
                $user_update["vip_effective_time"] = $vip_effective_time;
            }elseif($goods_info->type == 2) {
                $recharge_type  = 5;
                $log_name = $goods_info->name;
                #购买整个剧集
                $playlet_id = $order_info->playlet_id;
                if($playlet_id == 0) {
                    var_dump('没有剧集');
                    return false;
                }
                #查询所有剧集
                $playlet_episodes = Db::table("playlet_episodes")->where('playlet_id',$playlet_id)->get();
                #去掉已购买该剧集的
                $my_playlet_episodes = $this->playletService->get_my_playlet_episodes($applet_id,$user_id,$playlet_id);
                $table_name = "data_user_".$applet_id;
                foreach ($playlet_episodes as $key => $val) {
                    if (!in_array($val->playlet_number,$my_playlet_episodes)) {
//                        $order_id = $applet_id.$playlet_id.$val->playlet_number.$user_id;
                        $add_data = [
                            "user_id"=>$user_id,
                            "applet_id"=>$applet_id,
                            "playlet_id"=>$playlet_id,
                            "playlet_number"=>$val->playlet_number,
                            "amount"=>0,
                            "order_id"=>$order_id,
                        ];
                        Db::table("data_user_pay_playlet_log")->insertGetId($add_data);
                    }
                }
                $this->userService->update_user_info($applet_id,$user_id);
                $this->playletService->up_my_playlet_episodes($applet_id,$user_id,$playlet_id);
                #2024-02-23 合并剧集
                $this->playletService->set_merge_playlet_id($playlet_id,$user_id);
            }

            else{

                #+代币

                $user_update["ml_coin"] = $user_info->ml_coin + $order_info->ml_coin;
                $user_update["give_coin"] = $user_info->give_coin + $order_info->give_coin;
            }
            $user_table = "data_user_".$order_info->applet_id;
            $adds_data = [
                "user_id"=>$order_info->user_id,
                "applet_id"=>$order_info->applet_id,
                "amount"=>$order_info->amount,
                "stype"=>1,
                "is_vip"=>$order_info->is_vip,
                "ml_coin"=>$order_info->amount,
                "give_coin"=>$order_info->give_coin,
            ];
            $adds_log["name"] = $log_name;
            $adds_log["order_id"] = $order_id;
            $adds_log["user_id"] = $order_info->user_id;
            $adds_log["recharge_type"] = $recharge_type;
            $adds_log["stype"] = 1;
            $adds_log["applet_id"] = $order_info->applet_id;
            $adds_log["amount"] = $order_info->amount;
            $adds_log["give_coin"] = $order_info->give_coin;
            $adds_log["ml_coin"] = $order_info->ml_coin;
            Db::table("data_user_recharge_log")->insertGetId($adds_data);
            Db::table("data_user_log")->insertGetId($adds_log);
//            Db::table($user_table)->where([
//                "id"=>$user_id,
//            ])->update($user_update);
            if(!empty($user_update)) {
                Db::table($user_table)->where([
                    "id"=>$user_id,
                ])->update($user_update);
            }
            Db::table("data_payment")
                ->where([
                    'order_id'=>$order_id
                ])
            ->update([
                'status'=>2,
                'pay_type'=>$way,
                'pay_time'=>date("Y-m-d H:i:s",floor($pay_time / 1000)),
                'transaction_id'=>$transaction_id,
                'pay_remark'=>json_encode($recdata)
            ]);
            $this->userService->update_user_info($applet_id,$user_id);
//            $this->dyService->syn_order($applet_id,$user_info->xc_open_id,$order_id,$order_info->amount,$status=1);
            var_dump('支付成功---------------------------------');
            $hkey = 'orderback';
            $key = $order_id;
            $this->redis->hSet($hkey,$key,'ok');
            # 完成任务
//            $this->taskService->do_task($applet_id,$user_id,4);
        });

    }
    public function dy_check_order($order_id,$xc_open_id) {
        $order_info  = Db::table("data_payment")->where(["order_id"=>$order_id])->first();
        $applet_id = $order_info->applet_id;
        $res = $this->dyService->syn_order($applet_id,$xc_open_id,$order_id,$order_info->amount,$status=2);
        return $res;
    }
    public function order_back($order_id=0) {
        if ($order_id == 0) {
            return false;
        } else {
            $hkey = 'orderback';
            $key = $order_id;
            $res = $this->redis->hGet($hkey,$key);
            if($res) {
                return true;
            } else {
                return false;
            }
        }
    }
    public function present_currency($applet_id,$xc_open_id,$order_id,$amount,$type=1) {
        $res = $this->commService->present_currency($applet_id,$xc_open_id,$order_id,$amount,$type);
        var_dump('加币');
        var_dump($res);
        return $res;
    }

}